/*
 * @Author: 颜礼田 yanlitian@carleagroup.com
 * @Date: 2024-08-14 17:19:38
 * @LastEditors: 颜礼田 2564217790@qq.com
 * @LastEditTime: 2024-09-07 10:53:36
 * @FilePath: \server\src\middleware\request.middleware.ts
 * @Description:
 */
import { Middleware, IMiddleware, Config } from '@midwayjs/core';
import { ForbiddenError } from '@midwayjs/core/dist/error/http';
import { NextFunction, Context } from '@midwayjs/koa';
import * as md5 from 'md5';
import { isNotEmpty } from '../utils/isHelper';

@Middleware()
export class RequestMiddleware implements IMiddleware<Context, NextFunction> {
  @Config('keys')
  key: string;

  @Config('iForbidderRoute')
  iForbidderRoute: Array<string>;

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      const { time, sign } = ctx.header;
      if (isNotEmpty(time) && isNotEmpty(sign)) {
        const secret = md5(`${md5(time)}-${this.key}`);
        if (sign === secret) {
          const result = await next();
          return result;
        }
      }

      throw new ForbiddenError('无权访问');
    };
  }

  ignore(ctx: Context) {
    return this.iForbidderRoute.includes(ctx.path);
  }

  static getName(): string {
    return 'request';
  }
}
